package com.tomtop.core.datasource.core;

import java.util.Optional;


public abstract class Proxy {
    public static <T> Optional<T> slave(SwitchExecute<T> runnable) {
    	DynamicDataSource.useSlave();
    	return execute(runnable);
	}
    
    public static <T> Optional<T> master(SwitchExecute<T> runnable) {
    	DynamicDataSource.useMaster();
    	return execute(runnable);
	}
    
   private static <T> Optional<T> execute(SwitchExecute<T> runnable) {
    	try {
    		return Optional.ofNullable(runnable.run());
		} catch (Throwable e) {
			throw new RuntimeException(e);
		}finally {
			DynamicDataSource.reset();
		}
	}
    
    @FunctionalInterface
    public static interface SwitchExecute<T>{ T run () throws Throwable;  }
}
